struct ListNode {
  int val;
  ListNode *next;
  ListNode() : val(0), next(nullptr) {}
  ListNode(int x) : val(x), next(nullptr) {}
  ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode *removeNthFromEnd(ListNode *head, int n) {
  ListNode *q = head, *s = head;
  ListNode *t = nullptr;
  for (int i = 0; i < n; i++) {
    q = q->next;
  }
  if (q == nullptr) {
    t = head->next;
    delete head;
    head = t;
    return head;
  }
  while (q->next != nullptr) {
    s = s->next;
    q = q->next;
  }
  t = s->next;
  s->next = s->next->next;
  delete t;
  return head;
}